package cn.chencq.spider.novel.utils;

import java.util.HashMap;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;

import com.alibaba.fastjson.JSONObject;

/**
 * 将小说数据存储到parse服务
 * 
 * @author ccq@chencq.cn
 *
 */
public class ParseUtils {

	private static final String BASE = "http://parse.chencq.cn/parse/classes/";

	/**
	 * 返回 objectId
	 * 
	 * @param className
	 * @param object
	 * @return
	 */
	public static String save(String className, Object object) {
		String url = BASE + className;
		String objectId = null;
		Map<String, String> headers = new HashMap<>();
		headers.put("Content-Type", "application/json");
		headers.put("X-Parse-Application-Id", "myAppId");
		headers.put("X-Parse-REST-API-Key", "myRestKey");
		headers.put("X-Parse-Master-Key", "myMasterKey");
		String result = HttpClientUtil.sendHttpPostJson(url, JSONObject.toJSONString(object), headers);
		if (StringUtils.isNotEmpty(result)) {
			JSONObject res = JSONObject.parseObject(result);
			objectId = res.getString("objectId");
		}
		return objectId;
	}

	public static JSONObject queryByPage(String className, int pageNo, int pageSize) {
		String url = BASE + className + "?order=createdAt&limit=" + pageSize + "&skip=" + (pageNo - 1) * pageSize + "&count=true";
		JSONObject res = null;
		Map<String, String> headers = new HashMap<>();
		headers.put("Content-Type", "application/json");
		headers.put("X-Parse-Application-Id", "myAppId");
		headers.put("X-Parse-REST-API-Key", "myRestKey");
		headers.put("X-Parse-Master-Key", "myMasterKey");
		String result = HttpClientUtil.sendHttpGet(url, null, headers);
		if (StringUtils.isNotEmpty(result)) {
			res = JSONObject.parseObject(result);
		}
		return res;
	}

	public static JSONObject queryByParam(String className, String where){
		String url = BASE + className + "?where=" + where;
		JSONObject res = null;
		Map<String, String> headers = new HashMap<>();
		headers.put("Content-Type", "application/json");
		headers.put("X-Parse-Application-Id", "myAppId");
		headers.put("X-Parse-REST-API-Key", "myRestKey");
		headers.put("X-Parse-Master-Key", "myMasterKey");
		String result = HttpClientUtil.sendHttpGet(url, null, headers);
		if (StringUtils.isNotEmpty(result)) {
			res = JSONObject.parseObject(result);
		}
		return res;
	}

}
